import os
import re

from lib.tools import tools
from lib.tools import mrtools
from lib.log.Logger import LOGGER

log = LOGGER


def main():
    lm = LawMatch('D://Code//PrivacyPolicy//Privacy2Policy//淘宝answer.txt',
                  'D://Code//PrivacyPolicy//Privacy2Policy//analyzeresult_淘宝.txt',
                  '网上购物')
    lm.printResult()
    pass


def _inLMList(s, list2):
    for ss in list2:
        if mrtools.equalPi(s, ss):
            return True

    return False


def _getPisfromStr(line: str):
    pipattern = re.compile(r'<(.*?)>')
    piobj = pipattern.findall(line)

    return piobj


def _getPisfromFile(path):
    result = []
    f = open(path, 'r', encoding='utf-8')
    for line in f.readlines():
        result.extend(_getPisfromStr(line.strip()))

    return result


def _verify(listrule, listres, compliance, uncompliance):
    for s in listres:
        if _inLMList(s, listrule):
            compliance.append(s)
        else:
            uncompliance.append(s)

    pass


def _prettyPrint(liststring):
    result = ""
    i = 0
    while i < len(liststring):
        string = liststring[i]
        length = len(string)
        j = i + 1
        while j < len(liststring):
            if length + len(liststring[j]) < 45:
                string = string + "、" + liststring[j]
                length = len(string)
            else:
                string = string + "、"
                break
            j = j + 1
        i = j
        string = string + "\n"
        result = result + string

    return result


class LawMatch:
    __label = ''
    __business = ''
    __pianspath = ''
    __pirespath = ''
    __pians = None
    __pires = None
    __pirule = None

    def __init__(self, pianspath: str = '', pirespath: str = '', business: str = ''):

        self.release()

        if pirespath == '':
            log.error('err: pi result path is null')
            return

        if tools.isAbsPath(pirespath):
            self.__pirespath = pirespath
        else:
            self.__pirespath = tools.getAbsPathFromRoot(pirespath)

        match = re.match(r'^.*[/\\]analyzeresult_(.*)\.txt', self.__pirespath, re.M)
        self.__label = match.group(1)

        self.__business = business
        self.__pires = _getPisfromFile(self.__pirespath)

        if pianspath != '':
            if tools.isAbsPath(pianspath):
                self.__pianspath = pianspath
            else:
                self.__pianspath = tools.getAbsPathFromRoot(pianspath)

            self.__pians = _getPisfromFile(self.__pianspath)

        self.__pirule = []
        rukepipath = tools.getAbsPathFromRoot('./data/rule/business/' + self.__business + '/pi.txt')
        f = open(rukepipath, 'r', encoding='utf-8')
        for line in f.readlines():
            self.__pirule.append(line.strip())

        pass

    def release(self):
        self.__label = ''
        self.__business = ''
        self.__pianspath = ''
        self.__pirespath = ''
        self.__pians = None
        self.__pires = None

        pass

    def printResult(self):
        # todo output path
        outputpath = tools.getAbsPathFromRoot('./output/finalresult_' + self.__label + '.txt')
        output = open(outputpath,
                      mode=('a' if os.path.exists(outputpath) else 'w'),
                      encoding='utf-8')

        answer_compliance = []
        answer_uncompliance = []
        _verify(self.__pirule, self.__pires, answer_compliance, answer_uncompliance)

        true_pi = []
        for s in self.__pires:
            if _inLMList(s, self.__pians):
                true_pi.append(s)

        result_compliance = []
        result_uncompliance = []
        _verify(self.__pirule, true_pi, result_compliance, result_uncompliance)

        if len(result_uncompliance) > 0:
            print(self.__label + "隐私政策在" + self.__business + "业务功能方面收集的个人信息违背了最少信息原则", file=output)
        else:
            print(self.__label + "隐私政策在" + self.__business + "业务功能方面收集的个人信息满足最少信息原则", file=output)
        print("\n<---------------------------------------------------------------------------------->\n", file=output)

        print("tool1标注结果分析：", file=output)
        num = str(len(true_pi))
        print("tool1正确提取的个人信息共" + num + "条，正确提取比例为" +
              str('{:.2%}'.format(len(true_pi) / len(self.__pians))), file=output)
        print("", file=output)

        print("tool1正确提取的个人信息中，满足最少信息原则的共" + str(len(result_compliance)) + "条\n如下所示：", file=output)
        print(_prettyPrint(result_compliance), file=output)
        print("", file=output)

        print("tool1正确提取的个人信息中，不满足最少信息原则的共" + str(len(result_uncompliance)) + "条\n如下所示：", file=output)
        print(_prettyPrint(result_uncompliance), file=output)
        print("", file=output)

        miss_list = [string for string in self.__pians if not _inLMList(string, true_pi)]
        print("tool1产生的漏报共" + str(len(miss_list)) + "条\n如下所示：", file=output)
        print(_prettyPrint(miss_list), file=output)
        print("", file=output)

        extra_list = [string for string in self.__pires if not _inLMList(string, self.__pians)]
        print("tool1产生的误报共" + str(len(extra_list)) + "条\n如下所示：", file=output)
        print(_prettyPrint(extra_list), file=output)

        print("\n<---------------------------------------------------------------------------------->\n", file=output)

        print("手工标注结果分析：", file=output)
        print("隐私政策声明中，满足最少信息原则的信息收集共" + str(len(answer_compliance)) + "条\n如下所示:", file=output)
        print(_prettyPrint(answer_compliance), file=output)
        print("", file=output)

        print("隐私政策声明中，不满足最少信息原则的信息收集共" + str(len(answer_uncompliance)) + "条\n如下所示:", file=output)
        print(_prettyPrint(answer_uncompliance), file=output)
        print("", file=output)

        output.flush()
        output.close()
        pass


if __name__ == '__main__':
    main()
